package thread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

//自行实现一个简单的线程池，只实现固定数量的线程池
class MyFixedThreadPool{
    private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

    public MyFixedThreadPool(int n){
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(() -> {
                //每个线程要完成的工作，就是从队列中取元素
                try {
                    while (true) {
                        Runnable task = queue.take();
                        task.run();
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            });
            t.start();
        }
    }
    public void submit(Runnable task) throws InterruptedException{
        //把任务添加到队列中    
        queue.put(task);
    }
}
public class demo35 {
    public static void main(String[] args) throws InterruptedException {
        MyFixedThreadPool threadPool = new MyFixedThreadPool(4);
        for (int i = 0; i < 100; i++) {
            int id = i;
            threadPool.submit(()->{
                System.out.println("执行任务" + id);
            });
        }
    }
    
}
